﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Cache
{
	public class RoleRightCache
	{
		public static readonly RoleRightCache Instance = new RoleRightCache();
		private RoleRightCache()
		{ }

		private object SyncRoot = new object();
		private IList<View_RoleRightList> _CacheList = null;
		public IList<View_RoleRightList> CacheList
		{
			get
			{
				if (_CacheList == null || _CacheList.Count == 0)
				{
					ReLoadFromDB();
				}
				return _CacheList;
			}
		}

		private void ReLoadFromDB()
		{
			Expression<Func<View_RoleRightList, bool>> f = (p => true);
			Expression<Func<View_RoleRightList, string>> o = (p => p.RoleName);
			var systemMapList = DAL.DALHelper.Instance.GetList<View_RoleRightList, string>(f, o, true);
			lock (SyncRoot)
			{
				_CacheList = new List<View_RoleRightList>();
				foreach (var item in systemMapList)
				{
					if (!_CacheList.Contains(item))
					{
						_CacheList.Add(item);
					}
				}
			}
		}

		public IList<View_RoleRightList> this[string roleName]
		{
			get
			{
				IList<View_RoleRightList> list = new List<View_RoleRightList>();
				lock(SyncRoot)
				{
					list = CacheList.Where(p => p.RoleName == roleName).ToList();
				}
				return list;
			}
		}

		public void Clear()
		{
			lock (SyncRoot)
			{
				if(_CacheList != null)
				{
					_CacheList.Clear();
				}
			}
		}
	}
}